﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace FileCopy
{
    class RenameStatus
    {
        public string sOldPath;
        public string sNewPath;
        public string sMessage;
        public int iFind;
        public int iFail;
        public int iTotal;
        public bool bSuccess;
        public RenameStatus(string _oldpath,string _newpath,string _message,int _find,int _fail,int _total,bool _success)
        {
            sOldPath = _oldpath;
            sNewPath = _newpath;
            sMessage = _message;
            iFind = _find;
            iFail = _fail;
            iTotal = _total;
            bSuccess = _success;
        }
    }
    class RenameFile
    {
        mainForm myForm;
        string path;
        string ext;
        RenameStatus rsStatus;
        delegate void SetTextCallback(RenameStatus status);//设置委托
        //初始化
        public RenameFile(mainForm _myForm,string _path,string _ext)
        {
            myForm = _myForm;
            path = _path;
            ext = _ext;
        }
        //重命名预览
         public void renamePreview()
         {
             Rename(true);
         }
         //
        public void renameExec(){
            Rename(false);
        }
        /// <summary>
        /// 重命名文件
        /// </summary>
        /// <param name="bPreview"></param>
        public void Rename(bool bPreview)
        {
            int iFind;
            int iTotal;
            int iFail;
            try
            {
                int PREVIEW_MAX=20;//预览上限
                //查找文件
                string[] subdir=Directory.GetDirectories(path);
                iFind = 0;
                iTotal = myForm.dgvRenameMap.Rows.Count;
                iFail = 0;
                //读取表格内第一个文件名
                for (int i = 0; i < iTotal; i++)
                {
                    int count=0;
                    //先在当前目录找
                    string filename = myForm.dgvRenameMap.Rows[i].Cells["OldName"].Value.ToString() + ext ;
                    string newname=myForm.dgvRenameMap.Rows[i].Cells["NewName"].Value.ToString() + ext ;
                    string sFilePath= path + "\\" + filename;
                    while (!File.Exists(sFilePath) && count < subdir.Length)
                    {
                        sFilePath=subdir[count]+"\\"+filename;
                        count++;
                    }
                    string sMessage = "";
                    bool bSuccess = true;
                    //如果找到了文件
                    if (File.Exists(sFilePath))
                    {
                        iFind++;
                          
                        //如果是预览，并且达到上限了，就退出
                        string sNewPath;
                        sNewPath = Path.GetDirectoryName(sFilePath) + "\\" + newname;
                        if (!File.Exists(sNewPath))
                        {
                            sMessage = "成功！";
                            bSuccess = true;
                            if (bPreview)
                            {
                                if (i >= PREVIEW_MAX)
                                    return;
                            }
                            else
                            {
                                File.Move(sFilePath, sNewPath);
                            }
                        }
                        else
                        {
                            sMessage = "存在同名目标文件！";
                        }
                        rsStatus = new RenameStatus(sFilePath, sNewPath, sMessage, iFind, iFail, iTotal, bSuccess);
                        setWorkStatus(rsStatus);
                    }
                    else
                    {
                        iFail++;
                        sMessage = "未找到源文件";
                        bSuccess = false;
                        rsStatus = new RenameStatus(filename, "", sMessage, iFind, iFail, iTotal, bSuccess);
                        setWorkStatus(rsStatus);
                    }
                }
                if(!bPreview)
                    MessageBox.Show(iFind+"个文件已重命名,"+iFail+"个文件失败！");
            }
            catch (Exception ex)
            {
                rsStatus = new RenameStatus("重命名出错！" + ex.Message.ToString(), "", "", 0, 0, 0, true);
                setWorkStatus(rsStatus);
            }      
            
        }
        public void setWorkStatus(RenameStatus status)
        {
            //来设置工作状态，解决多线程下不能设置问题
            try
            {
                if (myForm.InvokeRequired)
                {
                    SetTextCallback d = new SetTextCallback(setWorkStatus);
                    myForm.Invoke(d, new object[] { status });

                }
                else
                {
                    if (status.iTotal == 0)
                    {
                        myForm.tsslStatus.Text = status.sOldPath;
                        myForm.btRenameExec.Text = "执行命名";
                    }
                    else
                    {
                        myForm.dgvRenameResult.Rows.Add(status.sOldPath, status.sNewPath, status.sMessage);
                        myForm.tsslStatus.Text = status.sOldPath + "已重命名，完成" + (status.iFind + status.iFail) + "/" + status.iTotal + "，未找到对应" + status.iFail + "个。";

                        //没有找到文件，就添加到未找到列表里面
                        if (!status.bSuccess)
                        {
                            myForm.tsslStatus.Text = status.sOldPath + "未找到对应，完成" + (status.iFind + status.iFail) + "/" + status.iTotal + "，失败" + status.iFail + "个。";
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                string info = ex.Message + ex.Data;

                MessageBox.Show(info);

            }

        }
    }
}
